/*

 * Copyright (c) 2017-2018, FastDev 刘强 (fastdev@163.com).

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

package of.hotswapinject.core.common;

import com.alibaba.fastjson.JSONObject;
import of.hotswapinject.core.common.Const;

import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

public class ConfigUtil {
    private static JSONObject jarConfig;
    private static JSONObject fileConfig;
    // String jarFile = getLocalJarPath(ConfigUtil.class);
    public static void init(String jarFile) {
        try {
            String filePath = getJarDir(jarFile) + Const.FILESEPARATOR + "of.hotswapinject.json";
            String content = getResourceContent(new JarFile(jarFile), "of.hotswapinject.json");
            jarConfig = JSONObject.parseObject(content);
            String fileContent = getResourceContent(filePath);
            if(fileContent != null) {
                fileConfig = JSONObject.parseObject(fileContent);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String getLocalJarPath(Class cl) {
        URL localUrl = cl.getProtectionDomain().getCodeSource().getLocation();
        String path = null;
        try {
            path = URLDecoder.decode(
                    localUrl.getFile().replace("+", "%2B"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return path;
    }


    public static String getConfig(String key) {
        String config = System.getProperty(key);
        if(config != null && !"".equals(config)) {
            return config;
        }
        Object jobj = getConfig(fileConfig, key);
        if(jobj != null) {
            return jobj.toString();
        }

        jobj = getConfig(jarConfig, key);
        if(jobj != null) {
            return jobj.toString();
        }
        return null;
    }

    public static Object getConfig(JSONObject jobj, String key) {
        if(jobj == null) {
            return null;
        }
        if(key == null || "".equals(key)) {
            return null;
        }
        String[] arr = key.split("\\.");
        if(arr.length == 0) {
            return null;
        }
        for(int i1 = 0; i1 < arr.length - 1; i1++) {
            String part = arr[i1];
            if(part == null || "".equals(part)) {
                return null;
            }
            Object obj = jobj.get(part);
            if(obj instanceof JSONObject) {
                jobj = (JSONObject) obj;
            }
            else {
                return null;
            }
            if(jobj == null) {
                return null;
            }
        }
        return jobj.get(arr[arr.length - 1]);
    }

    public static String getJarDir(String jarPath) {
        int findSep = jarPath.lastIndexOf(Const.FILESEPARATOR);
        return jarPath.substring(0, findSep);
    }

    public static String getResourceContent(String path) throws IOException {
        File file = new File(path);
        if(file.exists()) {
            FileInputStream fis = new FileInputStream(file);
            try {
                return getResourceContent(fis);
            }
            finally {
                fis.close();
            }
        }
        return null;
    }

    public static String getResourceContent(InputStream stream) throws IOException {
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            isr = new InputStreamReader(stream, "UTF-8");
            br = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            String lineSeparator = System.getProperty("line.separator");
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append(lineSeparator);
            }
            String content = sb.toString();
            System.out.println("content is:" + content);
            return content;
        }
        finally {
            if(isr != null) {
                isr.close();
            }
            if(br != null) {
                br.close();
            }
        }
    }

    public static String getResourceContent(JarFile jarFile, String resourcePath) throws IOException {
        ZipEntry entry = jarFile.getEntry(resourcePath);
        if(entry == null) {
            return null;
        }
        InputStream stream = jarFile.getInputStream(entry);
        try {
            return getResourceContent(stream);
        }
        finally {
            stream.close();
        }
    }
}